import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import prisma from '@/app/lib/prisma';
import { verifyToken } from '@/app/lib/auth';
import { use } from 'react';

// 获取单条记录
export async function GET(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const params = await context.params;
    
    // 确保 params.id 存在
    if (!params?.id) {
      return NextResponse.json(
        { message: '记录ID不能为空' },
        { status: 400 }
      );
    }

    const cookieStore = await cookies();
    const token = cookieStore.get('auth-token')?.value;

    if (!token) {
      return NextResponse.json(
        { message: '请先登录后再使用此功能' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { message: '登录已过期，请重新登录' },
        { status: 401 }
      );
    }

    const record = await prisma.dietRecord.findFirst({
      where: {
        id: params.id,
        userId: payload.userId,
      },
      select: {
        id: true,
        date: true,
        mealType: true,
        foods: true,
        calories: true,
        protein: true,
        carbs: true,
        fat: true,
      },
    });

    if (!record) {
      return NextResponse.json(
        { message: '记录不存在' },
        { status: 404 }
      );
    }

    // 确保返回的数据格式正确
    const formattedRecord = {
      ...record,
      date: record.date.toISOString(),
      foods: Array.isArray(record.foods) ? record.foods : JSON.parse(record.foods as string),
    };

    return NextResponse.json({ record: formattedRecord });
  } catch (error) {
    console.error('获取饮食记录错误:', error);
    return NextResponse.json(
      { message: '获取记录失败' },
      { status: 500 }
    );
  }
}

// 更新记录
export async function PUT(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const params = await context.params;
    const cookieStore = await cookies();
    const token = cookieStore.get('auth-token')?.value;

    if (!token) {
      return NextResponse.json(
        { message: '请先登录后再使用此功能' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { message: '登录已过期，请重新登录' },
        { status: 401 }
      );
    }

    const data = await request.json();

    // 计算总热量和营养素
    const totalCalories = data.foods.reduce((sum: number, food: any) => sum + food.calories, 0);
    const totalProtein = data.foods.reduce((sum: number, food: any) => sum + food.protein, 0);
    const totalCarbs = data.foods.reduce((sum: number, food: any) => sum + food.carbs, 0);
    const totalFat = data.foods.reduce((sum: number, food: any) => sum + food.fat, 0);

    const record = await prisma.dietRecord.update({
      where: {
        id: params.id,
        userId: payload.userId,
      },
      data: {
        date: new Date(data.date),
        mealType: data.mealType,
        foods: JSON.stringify(data.foods),
        calories: totalCalories,
        protein: totalProtein,
        carbs: totalCarbs,
        fat: totalFat,
      },
    });

    // 返回格式化的记录
    const formattedRecord = {
      ...record,
      date: record.date.toISOString(),
      foods: JSON.parse(record.foods as string),
    };

    return NextResponse.json({ record: formattedRecord });
  } catch (error) {
    console.error('更新饮食记录错误:', error);
    return NextResponse.json(
      { message: '更新记录失败' },
      { status: 500 }
    );
  }
}

// 删除记录
export async function DELETE(
  request: Request,
  context: { params: Promise<{ id: string }> }
) {
  try {
    const params = await context.params;
    const cookieStore = await cookies();
    const token = cookieStore.get('auth-token')?.value;

    if (!token) {
      return NextResponse.json(
        { message: '请先登录后再使用此功能' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { message: '登录已过期，请重新登录' },
        { status: 401 }
      );
    }

    await prisma.dietRecord.delete({
      where: {
        id: params.id,
        userId: payload.userId,
      },
    });

    return NextResponse.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除饮食记录错误:', error);
    return NextResponse.json(
      { message: '删除记录失败' },
      { status: 500 }
    );
  }
} 